package com.wpzf.ndhc.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.nacos.shaded.com.google.gson.Gson;
import com.wpzf.common.core.utils.StringUtils;
import com.wpzf.common.core.web.domain.AjaxResult;
import com.wpzf.ndhc.domain.*;
import com.wpzf.ndhc.mapper.*;
import com.wpzf.ndhc.service.WpzfNdhcInfoTranslateService;
import com.wpzf.ndhc.utils.CheckUtil;
import com.wpzf.ndhc.utils.DBUtil;
import com.wpzf.ndhc.utils.LogUtil;
import com.wpzf.ndhc.utils.MyObjectUtil;
import com.wpzf.zxhc.mapper.WpzfDockMapper;
import com.wpzf.zxhc.utils.OBSUploadUnits;
import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.SecureRandom;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.atomic.AtomicInteger;

@RestController
@Configuration
@EnableScheduling
@RequestMapping("tt")
public class SchedulingConfigurer {

    @Autowired
    private WpzfNdhcInfoTranslateService wpzfNdhcInfoTranslateServiceImpl;

    @Autowired
    private WpSjsbNdDTOMapper wpSjsbNdDTOMapper;

    @Autowired
    private WpzfDockMapper wpzfDockMapper;

    @Value("${exepath}")
    public String exePath;

    @Autowired
    private SqlSessionFactory sqlSessionFactory;


    @RequestMapping("t1")
    public AjaxResult t1() {
        List<Map<String, Object>> list = wpzfNdhcInfoTranslateServiceImpl.t1();
        Integer rest = 0;
        for (Map<String, Object> map : list) {
            String params = map.get("params") + "";
            Map<String, Object> map1 = new HashMap<>();
            // 去除首尾的大括号
            String[] pairs = params.substring(1, params.length() - 1).split(", ");
            for (String pair : pairs) {
                String[] keyValue = pair.split("=");
                if (keyValue.length == 2) {
                    map1.put(keyValue[0], keyValue[1]);
                }
            }
            Map<String, Object> m = new HashMap<>();
            m.put("uuid", map.get("uuid"));
            m.put("dkbh", map1.get("tbbh"));
            m.put("xzqdm", map1.get("xzqdm"));
            m.put("state", map1.get("state"));
            m.put("gtytime", map1.get("createtime"));
            rest += wpzfNdhcInfoTranslateServiceImpl.update(m);
        }
        return AjaxResult.success("成功", rest);
    }

    //存储地块信息
//    @Scheduled(fixedDelay = 600000)
    public void saveNdDbInfo() {
        String logUrl = null;
        try {
            Properties properties = new Properties();//获取Properties实例
            InputStream inStream = SchedulingConfigurer.class.getClassLoader().getResourceAsStream("config/log.properties");//获取配置文件输入流
            properties.load(inStream);//载入输入流
            logUrl = properties.getProperty("logToTxtUrl.scheduledTasks.saveNdDkInfo");

            LogUtil.logToTxt("\n", logUrl);
            LogUtil.logToTxt("定时开始", logUrl);

            Gson gson = new Gson();

            //查询状态为0的logUrl
            List<Map<String, Object>> impList1 = wpzfNdhcInfoTranslateServiceImpl.queryStatusdk();
            if (impList1 != null && impList1.size() > 0) {
                for (int i = 0; i < impList1.size(); i++) {
                    LogUtil.logToTxt("第" + (i + 1) + "条数据开始", logUrl);

                    Map<String, Object> imp = impList1.get(i);
                    LogUtil.logToTxt(imp.get("params").toString(), logUrl);
                    String jsonString = imp.get("params").toString();
                    Map<String, Object> map = new HashMap<>();
                    // 去除首尾的大括号
                    String[] pairs = jsonString.substring(1, jsonString.length() - 1).split(", ");
                    for (String pair : pairs) {
                        String[] keyValue = pair.split("=");
                        if (keyValue.length == 2) {
                            map.put(keyValue[0], keyValue[1]);
                        }
                    }
                    //存储地块 附件 批文信息
                    List<Map<String, Object>> list = wpzfNdhcInfoTranslateServiceImpl.queryPushNdDkLogToStatus(map);
                    if (list != null && list.size() > 0) {
                        int k = wpzfNdhcInfoTranslateServiceImpl.updateStatusdk(imp);
                    } else {
                        AjaxResult ajaxResult = getnddkxxbsjInfo2024(map, logUrl);
                        if (ajaxResult.get("code").equals(200)) {
                            LogUtil.logToTxt(ajaxResult.get("code").toString(), logUrl);
                            //更新状态
                            int k = wpzfNdhcInfoTranslateServiceImpl.updateStatusdk(imp);
                            if (k > -1) {
                                LogUtil.logToTxt("状态更新成功," + k, logUrl);
                            }
                        } else {
                            LogUtil.logToTxt("地块处理失败：" + ajaxResult.get("msg"), logUrl);
                        }
                    }


                    LogUtil.logToTxt("第" + (i + 1) + "条数据结束", logUrl);
                }
            }
        } catch (Exception e) {
            System.err.println(e.getMessage());
        } finally {
            LogUtil.logToTxt("定时结束", logUrl);
        }
    }

    public AjaxResult getnddkxxbsjInfo2024(Map<String, Object> map, String logUrl) {
        try {
            String xzqdm = map.get("xzqdm") + "";
            String tbbh = map.get("tbbh") + "";
            String state = map.get("state") + "";

            if (("-1").equals(state)) {
                //-1 为撤回 删除 dkxxb
                Map<String, Object> params = new HashMap<>();
                params.put("dkbh", tbbh);
                params.put("xzqdm", xzqdm);

                //删除
                WpSjsbDkjbxxNdDTO wpSjsbDkjbxxNdDTO = wpzfNdhcInfoTranslateServiceImpl.queryDkjbxxByDkbh(params);
                Integer i = wpzfNdhcInfoTranslateServiceImpl.deleteSjsbDkjbxxByBsm(wpSjsbDkjbxxNdDTO);
                wpzfNdhcInfoTranslateServiceImpl.deleteSjsbDkfjjbxxByDkbsm(wpSjsbDkjbxxNdDTO);
                wpzfNdhcInfoTranslateServiceImpl.deleteSjsbDkpwjbxxByDkbsm(wpSjsbDkjbxxNdDTO);
                wpzfNdhcInfoTranslateServiceImpl.deleteSjHcfjByDkbsm(wpSjsbDkjbxxNdDTO);

                wpzfNdhcInfoTranslateServiceImpl.deleteSjDkshshengjiNdByDkbsm(wpSjsbDkjbxxNdDTO);
                wpzfNdhcInfoTranslateServiceImpl.deleteSjDkshshengjiNdHftgzmwjByDkbsm(wpSjsbDkjbxxNdDTO);
                wpzfNdhcInfoTranslateServiceImpl.deleteSjDkshshengjiNdQtpzwhByDkbsm(wpSjsbDkjbxxNdDTO);
                wpzfNdhcInfoTranslateServiceImpl.deleteSjDkshshengjiNdQtsftgxxydssByDkbsm(wpSjsbDkjbxxNdDTO);
                wpzfNdhcInfoTranslateServiceImpl.deleteSjDkshshengjiNdQtsfzygdByDkbsm(wpSjsbDkjbxxNdDTO);
                wpzfNdhcInfoTranslateServiceImpl.deleteSjDkshshengjiNdWfpzwhByDkbsm(wpSjsbDkjbxxNdDTO);
                wpzfNdhcInfoTranslateServiceImpl.deleteSjDkshshengjiNdWftgzmwjByDkbsm(wpSjsbDkjbxxNdDTO);

                return AjaxResult.success(tbbh + "地块退回成功");
            } else {
                //默认为推送
                String postURL = "";
                String data = "";
                {
                    postURL = "https://jg.landcloud.org.cn:8553/webapi/token";
                    data = "client_id=web&client_secret=e46232c20609435eba54b7576de935dd&grant_type=password&username=a53e0c14ee900728f36bba014d975982&password=b30c775c48e9ba92ade95e427a5242b0";
                }
                URL url = new URL(postURL);
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setRequestMethod("POST");
                conn.setRequestProperty("accept", "*/*");
                conn.setRequestProperty("connection", "Keep-Alive");
                conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");

                conn.setDoOutput(true);
                conn.setDoInput(true);
                OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream(), "utf-8");

                out.write(data);
                //缓冲数据
                out.flush();
                //获取URLConnection对象对应的输入流
                InputStream is = conn.getInputStream();
                int count = 0;
                ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                byte[] buffer = new byte[4096];
                while ((count = is.read(buffer)) != -1) {
                    byteArrayOutputStream.write(buffer, 0, count);
                }
                byte[] datas = byteArrayOutputStream.toByteArray();
                byteArrayOutputStream.close();
                //关闭流
                is.close();
                conn.disconnect();
                String result = new String(datas, 0, datas.length, "utf-8");
                // 00gty_wpzf_nddk 年度地块
                String str = getNDDxxxbsj2024(result, "00gty_wpzfnddk2024", xzqdm, tbbh, logUrl); //年度地块信息
                if (str.equals("")) {
                    LogUtil.logToTxt(tbbh + "地块信息入库成功", logUrl);
                    //入库后 更新tbxxb的状态
                    return AjaxResult.success(tbbh + "地块入库成功");
                } else {
                    LogUtil.logToTxt(tbbh + "地块信息入库失败：" + str, logUrl);
                    return AjaxResult.error(tbbh + "地块入库失败:" + str);
                }
            }
        } catch (Exception ex) {
            return AjaxResult.error("地块处理失败" + ex.getMessage());
        }
    }

    @Transactional
    public String getNDDxxxbsj2024(String str, String ywmb, String xzqdm, String tbbh, String logUrl) {
        String rest = "";
        try {
            String postURL = "";
            String token = "";
            String token_type = "";
            Map mapType = JSON.parseObject(str, Map.class);
            {
                for (Object obj : mapType.keySet()) {

                    if ((obj + "").equals("access_token")) {
                        token = mapType.get("access_token") + "";
                        token_type = mapType.get("token_type") + "";
                    }
                }
                System.out.println(token);
                //接口地址
                postURL = "https://dc2.landcloud.org.cn:9443/webapi/api/open/GetWPZFTBInfo";
            }
            URL url = new URL(postURL);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            String encoding = com.wpzf.common.core.utils.sign.Base64.encode(str.getBytes());
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("Charset", "utf-8");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
            conn.setRequestProperty("Content-Type", "application/json;charset=utf-8 ");
            conn.setRequestProperty("Authorization", token_type + " " + token);
            //  conn.setRequestProperty("token", token);
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setConnectTimeout(20000);
            conn.setReadTimeout(20000);

            OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream(), "utf-8");
            if (StringUtils.isNotBlank(xzqdm)) {
                //String data = "{\"xzqdm\":\"" + xzqdm + "\",\"ywmb\":\"" + ywmb + "\"}";
                String data = "{\"xzqdm\":\"" + xzqdm + "\",\"ywmb\":\"" + ywmb + "\",\"xmbh\":[\"" + tbbh + "\"]}";
                System.out.println("---------获取地块列表参数------" + data);
                out.write(data);
                out.flush();
                InputStream is = conn.getInputStream();
                int count = 0;
                ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                byte[] buffer = new byte[4096];
                while ((count = is.read(buffer)) != -1) {
                    byteArrayOutputStream.write(buffer, 0, count);
                }
                byte[] datas = byteArrayOutputStream.toByteArray();

                byteArrayOutputStream.close();
                is.close();
                conn.disconnect();
                rest = new String(datas, 0, datas.length, "utf-8");
                JSONObject obj = JSONObject.parseObject(rest);
                if (obj.get("data") == null) {
                    rest = data + "获取地块信息为null";
                    return rest;
                }

                Map<String, Object> params = new HashMap<>();
                params.put("dkbh", tbbh);
                params.put("xzqdm", xzqdm);

                //删除
                WpSjsbDkjbxxNdDTO wpSjsbDkjbxxNdDTO = wpzfNdhcInfoTranslateServiceImpl.queryDkjbxxByDkbh(params);
                wpzfNdhcInfoTranslateServiceImpl.deleteSjsbDkjbxxByBsm(wpSjsbDkjbxxNdDTO);
                wpzfNdhcInfoTranslateServiceImpl.deleteSjsbDkfjjbxxByDkbsm(wpSjsbDkjbxxNdDTO);
                wpzfNdhcInfoTranslateServiceImpl.deleteSjsbDkpwjbxxByDkbsm(wpSjsbDkjbxxNdDTO);
                wpzfNdhcInfoTranslateServiceImpl.deleteSjHcfjByDkbsm(wpSjsbDkjbxxNdDTO);

                wpzfNdhcInfoTranslateServiceImpl.deleteSjDkshshengjiNdByDkbsm(wpSjsbDkjbxxNdDTO);
                wpzfNdhcInfoTranslateServiceImpl.deleteSjDkshshengjiNdHftgzmwjByDkbsm(wpSjsbDkjbxxNdDTO);
                wpzfNdhcInfoTranslateServiceImpl.deleteSjDkshshengjiNdQtpzwhByDkbsm(wpSjsbDkjbxxNdDTO);
                wpzfNdhcInfoTranslateServiceImpl.deleteSjDkshshengjiNdQtsftgxxydssByDkbsm(wpSjsbDkjbxxNdDTO);
                wpzfNdhcInfoTranslateServiceImpl.deleteSjDkshshengjiNdQtsfzygdByDkbsm(wpSjsbDkjbxxNdDTO);
                wpzfNdhcInfoTranslateServiceImpl.deleteSjDkshshengjiNdWfpzwhByDkbsm(wpSjsbDkjbxxNdDTO);
                wpzfNdhcInfoTranslateServiceImpl.deleteSjDkshshengjiNdWftgzmwjByDkbsm(wpSjsbDkjbxxNdDTO);

                String objdata = obj.get("data").toString();
                JSONArray arr = JSONArray.parseArray(objdata);
                LogUtil.logToTxt(objdata, logUrl);
                List<WpSjsbDkjbxxNdDTO> dkxxbsj2024DTOList = new ArrayList<>();
                List<WpSjHcfjNdDTO> wpSjHcfjNdDTOList = new ArrayList<>();
                List<WpSjsbDkfjjbxxNdDTO> wpSjsbDkfjjbxxNdDTOList = new ArrayList<>();
                List<WpSjsbDkpwjbbxxNdDTO> wpSjsbDkpwjbbxxNdDTOList = new ArrayList<>();
                if (arr.size() > 0) {
                    for (int i = 0; i < arr.size(); i++) {
                        JSONObject jsonObject = arr.getJSONObject(i);
                        JSONObject wpzfObject = jsonObject.getJSONObject("main").getJSONObject("wpzfdk");
                        JSONArray hcfjArray = jsonObject.getJSONObject("other").getJSONArray("hcfj");
                        JSONArray fjArray = jsonObject.getJSONObject("other").getJSONArray("fjinfo");
                        JSONArray pwArray = jsonObject.getJSONObject("other").getJSONArray("pwinfo");

                        //处理 普通信息
                        WpSjsbDkjbxxNdDTO model = new WpSjsbDkjbxxNdDTO();
                        String dkbsm = UUID.randomUUID().toString();
                        model.setBsm(dkbsm);
                        model.setTbbsm(wpzfObject.get("tbbsm").toString());
                        model.setXzqdm(wpzfObject.get("xzqdm").toString());

                        String xmc = wpzfNdhcInfoTranslateServiceImpl.getXmcByXzqdm(wpzfObject.get("xzqdm").toString());

                        model.setXmc(xmc);
                        model.setDkbh(wpzfObject.get("tbbh").toString());
                        model.setDkmc("");
                        model.setDkmj(MyObjectUtil.objectIsNullToDouble(wpzfObject.get("sjtbmj")));
//                        model.setXzb();
//                        model.setYzb();
                        model.setBz("");
                        model.setDkfw(wpzfObject.get("geometry").toString());

                        model.setXzjd(wpzfObject.get("xzmc").toString());
                        model.setCsmc(wpzfObject.get("csmc").toString());
                        model.setXxdz(wpzfObject.get("xxdz").toString());
                        model.setSfbgjsyd(wpzfObject.get("sfjsyd").toString());
                        model.setSfnrhsqd(wpzfObject.get("sfnrhsqd").toString());
                        model.setSfgdwf("");
                        model.setGdmj(MyObjectUtil.objectIsNullToDouble(wpzfObject.get("gdmj")));
                        model.setQtnydmj(MyObjectUtil.objectIsNullToDouble(wpzfObject.get("qtnydmj")));
                        model.setJsydmj(MyObjectUtil.objectIsNullToDouble(wpzfObject.get("jsydmj")));
                        model.setWlydmj(MyObjectUtil.objectIsNullToDouble(wpzfObject.get("wlydmj")));
                        model.setPdlx(wpzfObject.get("tblx").toString());
                        model.setHf_jtqx1(wpzfObject.get("sjyt").toString());
                        model.setHf_jtqx2(wpzfObject.get("sjyt2").toString());
                        model.setHf_sjyt(wpzfObject.get("hfsjyt").toString());
                        model.setHf_pdyjsm(wpzfObject.get("hfpdyjsm").toString());
                        model.setWf_wflx1(wpzfObject.get("wflx1").toString());
                        model.setWf_wflx2(wpzfObject.get("wflx2").toString());
                        model.setWf_sjyt(wpzfObject.get("wfsjyt").toString());
                        model.setSflzgdjf(wpzfObject.get("lzgdjf").toString());
                        model.setSfwhzj(wpzfObject.get("sywhzj").toString());
                        model.setSfdpf(wpzfObject.get("sfdpf").toString());
                        model.setWf_pdyjsm(wpzfObject.get("wfpdyjsm").toString());
                        model.setXmmc(wpzfObject.get("wf_xmmc").toString());
                        model.setXmzt(wpzfObject.get("wf_xmzt").toString());
                        model.setXmlx(wpzfObject.get("wf_xmlx").toString());
                        model.setLxpzjg(wpzfObject.get("wf_lxpzjg").toString());
                        model.setLxpzwh(wpzfObject.get("wf_lxpzwh").toString());
                        model.setWf_sfla(wpzfObject.get("wf_sfla").toString());
                        model.setQt_jtqx1(wpzfObject.get("qtydsjyt").toString());
                        model.setQt_jtqx2(wpzfObject.get("qtydsjyt2").toString());
                        model.setPwsj(wpzfObject.get("pwsj").toString());
                        model.setQt_pdyjsm(wpzfObject.get("qtpdyjsm").toString());

                        model.setNrqduserlevel(MyObjectUtil.objectIsNullToInteger(wpzfObject.get("nrqduserlevel").toString()));

                        //展开
                        model.setPch("年度卫片");
                        model.setDkzt("3");


                        if (hcfjArray != null && hcfjArray.size() > 0) {
                            for (int j = 0; j < hcfjArray.size(); j++) {
                                JSONObject hcfjObject = hcfjArray.getJSONObject(j);
                                WpSjHcfjNdDTO wpSjHcfjNdDTO = new WpSjHcfjNdDTO();
                                wpSjHcfjNdDTO.setBsm(Integer.parseInt(hcfjObject.get("bsm") + ""));
                                wpSjHcfjNdDTO.setDkbsm(dkbsm);
                                wpSjHcfjNdDTO.setXzqdm(hcfjObject.get("xzqdm") + "");
                                wpSjHcfjNdDTO.setTbbsm(hcfjObject.get("tbbsm") + "");
                                wpSjHcfjNdDTO.setTbbh(hcfjObject.get("tbbh") + "");
                                wpSjHcfjNdDTO.setFjmc(hcfjObject.get("fjmc") + "");
                                wpSjHcfjNdDTO.setLysb(hcfjObject.get("lysb") + "");
                                wpSjHcfjNdDTO.setFjlx(hcfjObject.get("fjlx") + "");
                                wpSjHcfjNdDTO.setPsry(hcfjObject.get("psry") + "");
                                wpSjHcfjNdDTO.setPssj(hcfjObject.get("pssj") + "");
                                wpSjHcfjNdDTO.setLongitude(MyObjectUtil.objectIsNullToDouble(hcfjObject.get("longitude")));
                                wpSjHcfjNdDTO.setLatitude(MyObjectUtil.objectIsNullToDouble(hcfjObject.get("latitude")));
                                wpSjHcfjNdDTO.setPsjd(Integer.parseInt(hcfjObject.get("psjd") + ""));
                                wpSjHcfjNdDTO.setPsgd(hcfjObject.get("psgd") + "");
                                if (("").equals(hcfjObject.get("psfyj"))) {
                                } else {
                                    wpSjHcfjNdDTO.setPsfyj(Integer.parseInt(hcfjObject.get("psfyj") + ""));
                                }
                                wpSjHcfjNdDTO.setPsaltitude(hcfjObject.get("psaltitude") + "");
                                wpSjHcfjNdDTO.setTakeofflon(hcfjObject.get("takeofflon") + "");
                                wpSjHcfjNdDTO.setTakeofflat(hcfjObject.get("takeofflat") + "");
                                wpSjHcfjNdDTO.setTakeoffrelheight(hcfjObject.get("takeoffrelheight") + "");
                                wpSjHcfjNdDTO.setTakeoffaltitude(hcfjObject.get("takeoffaltitude") + "");
                                wpSjHcfjNdDTO.setMetarecord(hcfjObject.get("metarecord") + "");
                                wpSjHcfjNdDTO.setArg(hcfjObject.get("arg") + "");
                                wpSjHcfjNdDTO.setUrl(hcfjObject.get("url") + "");

                                wpSjHcfjNdDTOList.add(wpSjHcfjNdDTO);
                            }
                        }

                        //处理附件信息
                        if (fjArray != null && fjArray.size() > 0) {
                            for (int j = 0; j < fjArray.size(); j++) {
                                JSONObject fjObject = fjArray.getJSONObject(j);
//                                WpSjsbFjNdDTO fjmodel = JSON.toJavaObject(fjObject, WpSjsbFjNdDTO.class);
                                WpSjsbDkfjjbxxNdDTO wpSjsbDkfjjbxxNdDTO = new WpSjsbDkfjjbxxNdDTO();
                                SecureRandom secureRandom = new SecureRandom();
                                // 生成一个 32 位的随机数
                                int randomInt = secureRandom.nextInt();
                                wpSjsbDkfjjbxxNdDTO.setBsm(randomInt);
                                wpSjsbDkfjjbxxNdDTO.setPwtbbsm(fjObject.get("pwtbbsm") + "");
                                wpSjsbDkfjjbxxNdDTO.setDkbsm(dkbsm);
                                wpSjsbDkfjjbxxNdDTO.setXzqdm(xzqdm);
                                wpSjsbDkfjjbxxNdDTO.setFjmc(fjObject.get("fjmc") + "");
                                wpSjsbDkfjjbxxNdDTO.setFjlx(fjObject.get("fjlx") + "");
                                wpSjsbDkfjjbxxNdDTO.setScry("");
                                wpSjsbDkfjjbxxNdDTO.setScsj("");
                                wpSjsbDkfjjbxxNdDTO.setFjdx(0);
                                wpSjsbDkfjjbxxNdDTO.setMd5("");
                                wpSjsbDkfjjbxxNdDTO.setUrl(fjObject.get("fjurl") + "");
                                wpSjsbDkfjjbxxNdDTOList.add(wpSjsbDkfjjbxxNdDTO);

                            }
                        }
                        //处理批文信息
                        if (pwArray != null && pwArray.size() > 0) {
                            for (int j = 0; j < pwArray.size(); j++) {
                                JSONObject pwObject = pwArray.getJSONObject(j);
//                                WpSjsbDkpwjbbxxNdDTO pwmodel = JSON.toJavaObject(pwObject, WpSjsbDkpwjbbxxNdDTO.class);
                                WpSjsbDkpwjbbxxNdDTO wpSjsbDkpwjbbxxNdDTO = new WpSjsbDkpwjbbxxNdDTO();
                                wpSjsbDkpwjbbxxNdDTO.setBsm(UUID.randomUUID().toString());
                                wpSjsbDkpwjbbxxNdDTO.setDkbsm(dkbsm);
                                wpSjsbDkpwjbbxxNdDTO.setXzqdm(xzqdm);
                                wpSjsbDkpwjbbxxNdDTO.setPwtbbsm(pwObject.get("pwtbbsm") + "");

                                wpSjsbDkpwjbbxxNdDTO.setPzwh(pwObject.get("pzwh") + "");
                                wpSjsbDkpwjbbxxNdDTO.setPzwhlx(pwObject.get("pzwhlx") + "");
                                wpSjsbDkpwjbbxxNdDTO.setPzwhlxtwo(pwObject.get("pzwhlxtwo") + "");
                                wpSjsbDkpwjbbxxNdDTO.setPzjg(pwObject.get("pzjg") + "");
                                wpSjsbDkpwjbbxxNdDTO.setPwly(Integer.parseInt(pwObject.get("pwly") + ""));
                                wpSjsbDkpwjbbxxNdDTO.setPzsj(pwObject.get("pzsj") + "");
                                wpSjsbDkpwjbbxxNdDTO.setPzmj(MyObjectUtil.objectIsNullToDouble(pwObject.get("pzmj")));
                                wpSjsbDkpwjbbxxNdDTO.setPzgdmj(MyObjectUtil.objectIsNullToDouble(pwObject.get("pzgdmj")));
                                wpSjsbDkpwjbbxxNdDTO.setPznydmj(MyObjectUtil.objectIsNullToDouble(pwObject.get("pznydmj")));
                                wpSjsbDkpwjbbxxNdDTO.setPzyjjbntmj(MyObjectUtil.objectIsNullToDouble(pwObject.get("pzyjjbntmj")));
                                wpSjsbDkpwjbbxxNdDTO.setMd5("");
                                wpSjsbDkpwjbbxxNdDTO.setReason(pwObject.get("reason") + "");
                                wpSjsbDkpwjbbxxNdDTOList.add(wpSjsbDkpwjbbxxNdDTO);
                            }
                        }

                        dkxxbsj2024DTOList.add(model);
                    }
                } else {
                    rest = "获取图斑信息失败";
                    return rest;
                }
                if (dkxxbsj2024DTOList.size() > 0) {
                    //先删除原有的
                    boolean b = InsertBatchdkxxbsj(dkxxbsj2024DTOList);
                    if (b) {
                        System.out.println(xzqdm + "成功导入图斑" + dkxxbsj2024DTOList.size() + "条");
                        b = InsertBatch1ndsj(wpSjHcfjNdDTOList);
                        System.out.println("成功导入核查附件" + wpSjHcfjNdDTOList.size() + "条");
                        b = InsertBatch2ndsj(wpSjsbDkfjjbxxNdDTOList);
                        System.out.println("成功导入地块附件" + wpSjsbDkfjjbxxNdDTOList.size() + "条");
                        b = InsertBatch3ndsj(wpSjsbDkpwjbbxxNdDTOList);
                        System.out.println("成功导入地块批文" + wpSjsbDkpwjbbxxNdDTOList.size() + "条");
                        rest = "";
                    } else {
                        rest = "导入失败";
                    }
                }
            }

        } catch (Exception e) {
            rest = "网络异常，请稍后重试！";
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return e.getMessage();
        }
        return rest;
    }

    @Transactional
    public boolean InsertBatchdkxxbsj(List<WpSjsbDkjbxxNdDTO> dkxxb2024DTOList) {
        SqlSession sqlSession = null;
        try {
            //使用批处理
            sqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH, false);
            WpSjsbDkjbxxNdMapper dkxxbMapper = sqlSession.getMapper(WpSjsbDkjbxxNdMapper.class);
            dkxxb2024DTOList.stream().forEach(dkxxbDao -> dkxxbMapper.insert(dkxxbDao));
            sqlSession.commit();
            return true;
        } catch (Exception ex) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            ex.printStackTrace();
            return false;
        } finally {
            // 确保SqlSession被关闭
            if (sqlSession != null) {
                sqlSession.close();
            }
        }
    }

    @Transactional
    public boolean InsertBatch1ndsj(List<WpSjHcfjNdDTO> wpSjHcfjNdDTOList) {
        SqlSession sqlSession = null;
        try {
            //使用批处理
            sqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH, false);
            WpSjHcfjNdMapper wpSjHcfjNdMapper = sqlSession.getMapper(WpSjHcfjNdMapper.class);
            wpSjHcfjNdDTOList.stream().forEach(hcfjDTO -> wpSjHcfjNdMapper.insert(hcfjDTO));
            sqlSession.commit();
            return true;
        } catch (Exception ex) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            ex.printStackTrace();
            return false;
        } finally {
            // 确保SqlSession被关闭
            if (sqlSession != null) {
                sqlSession.close();
            }
        }
    }

    @Transactional
    public boolean InsertBatch2ndsj(List<WpSjsbDkfjjbxxNdDTO> wpSjsbDkfjjbxxNdDTOList) {
        SqlSession sqlSession = null;
        try {
            //使用批处理
            sqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH, false);
            WpSjsbDkfjjbxxNdMapper wpSjsbDkfjjbxxNdMapper = sqlSession.getMapper(WpSjsbDkfjjbxxNdMapper.class);
            wpSjsbDkfjjbxxNdDTOList.stream().forEach(fjinfo2024DTO -> wpSjsbDkfjjbxxNdMapper.insert(fjinfo2024DTO));
            sqlSession.commit();
            return true;
        } catch (Exception ex) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            ex.printStackTrace();
            return false;
        } finally {
            // 确保SqlSession被关闭
            if (sqlSession != null) {
                sqlSession.close();
            }
        }
    }

    @Transactional
    public boolean InsertBatch3ndsj(List<WpSjsbDkpwjbbxxNdDTO> wpSjsbDkpwjbbxxNdDTOList) {
        SqlSession sqlSession = null;
        try {
            //使用批处理
            sqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH, false);
            WpSjsbDkpwjbbxxNdMapper wpSjsbDkpwjbbxxNdMapper = sqlSession.getMapper(WpSjsbDkpwjbbxxNdMapper.class);
            wpSjsbDkpwjbbxxNdDTOList.stream().forEach(pwinfo2024DTO -> wpSjsbDkpwjbbxxNdMapper.insert(pwinfo2024DTO));
            sqlSession.commit();
            return true;
        } catch (Exception ex) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            ex.printStackTrace();
            return false;
        } finally {
            // 确保SqlSession被关闭
            if (sqlSession != null) {
                sqlSession.close();
            }
        }
    }


    //年度省级推送数据打包成db进行质检
    //@Scheduled(fixedDelay = 10800000)
    public void qualityInspectionDb() {
        String logUrl = null;
        try {
            Properties properties = new Properties();//获取Properties实例
            InputStream inStream = SchedulingConfigurer.class.getClassLoader().getResourceAsStream("config/log.properties");//获取配置文件输入流
            properties.load(inStream);//载入输入流
            logUrl = properties.getProperty("logToTxtUrl.scheduledTasks.qualityInspectionDb");

            LogUtil.logToTxt("\n", logUrl);
            LogUtil.logToTxt("定时任务开始", logUrl);

            List<String> xzqdmList = wpSjsbNdDTOMapper.queryXzqdmToSjsbTbjbxx();

            //根据数据内所有行政区代码打包db
            DBUtil dbUtil = new DBUtil();
            for (String xzqdm : xzqdmList) {

                LogUtil.logToTxt("xzqdm：" + xzqdm, logUrl);

                Map<String, Object> dbresult = dbUtil.dbCreate(wpSjsbNdDTOMapper, xzqdm, "0");
                LogUtil.logToTxt("DB生成结果：" + dbresult, logUrl);

                String dburl = "";
                String logurl = "";
                String dbpassword = "";
                String message = "";
                String excelurl = "";
                String createtime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format((new Date()).getTime());

                if (dbresult.get("code").equals(200)) {
                    //02 DB创建成功 进行质检
                    String dbPath = dbresult.get("dbpath").toString();
                    String dbPass = dbresult.get("dbpass").toString();

                    dbpassword = dbPass;

                    CheckUtil checkUtil = new CheckUtil();
                    Map<String, Object> checkresult = checkUtil.chedktool(exePath, dbPath, dbPass);
                    message = checkresult.get("message") + "";
                    LogUtil.logToTxt("质检结果：" + checkresult, logUrl);
                    //通过质检 获取签章
                    if (checkresult.get("code").equals(200)) {
                        wpzfDockMapper.updateSjsbTbjbxxStatusByXzqdm(xzqdm);
                        message = "DB包质检成功"; //质检失败
                    } else {
                        message = "DB包质检失败"; //质检失败
                    }
                    String dbOBSAddress = "saveResult" + "/db/" + xzqdm + ".db";
                    AtomicInteger attemptCount1 = new AtomicInteger(0);
                    String dbOBSlog;
                    do {
                        dbOBSlog = OBSUploadUnits.OBSUpload(dbOBSAddress, dbPath);
                        attemptCount1.incrementAndGet();
                    } while (!dbOBSlog.equals("success") && attemptCount1.get() < 5);
                    dburl = "https://obs-top.obs.cn-north-1.myhuaweicloud.com/" + dbOBSAddress;

                    String logOBSAddress = "saveResult" + "/log/" + xzqdm + ".txt";
                    AtomicInteger attemptCount2 = new AtomicInteger(0);
                    if (checkresult.get("logpath")!=null) {
                        String txtOBSlog;
                        do {
                            txtOBSlog = OBSUploadUnits.OBSUpload(logOBSAddress, checkresult.get("logpath").toString());
                            attemptCount2.incrementAndGet();
                        } while (!txtOBSlog.equals("success") && attemptCount2.get() < 5);
                        logurl = "https://obs-top.obs.cn-north-1.myhuaweicloud.com/" + logOBSAddress;
                    }

                    Map<String, Object> checklog = checkUtil.chedklog(checkresult.get("logpath").toString(), xzqdm);
                    if (checklog.get("code").equals(200)) {
                        excelurl = checklog.get("excelPath").toString();
                    } else {
                        message = "DB日志解析失败";
                    }
                } else {
                    //DB创建失败
                    message = "DB创建失败," + dbresult.get("message").toString();
                }

                LogUtil.logToTxt("message：" + message, logUrl);

                Map<String, Object> m = new HashMap<>();
                m.put("xzqdm", xzqdm);
                m.put("dburl", dburl);
                m.put("logurl", logurl);
                m.put("dbpassword", dbpassword);
                m.put("message", message);
                m.put("createtime", createtime);
                m.put("excelurl", excelurl);
                wpzfDockMapper.saveQualityTestingLog(m);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            LogUtil.logToTxt("定时任务结束", logUrl);
        }
    }

//    @Scheduled(fixedDelay = 3600000)
    @RequestMapping(value = "/qualityInspection", method = RequestMethod.POST)
    public void qualityInspection() {
        List<String> xzqdmList = wpzfDockMapper.queryXzqdmToQualitytesting();
        ExecutorService executorService = Executors.newFixedThreadPool(5); // 创建一个固定大小的线程池
        List<Future<Void>> futures = new ArrayList<>();
        for (String xzqdm : xzqdmList) {
            Callable<Void> task = new Callable<Void>() {
                @Override
                public Void call() throws Exception {
                    DBUtil dbUtil = new DBUtil(); // 注意：如果DBUtil是线程安全的，则可以在循环外部创建单个实例；否则，应在任务内部创建
                    Map<String, Object> dbresult = dbUtil.getDBCreate(wpSjsbNdDTOMapper, xzqdm, "0");
                    Map<String, Object> map = new HashMap<>();
                    String dburl = "";
                    String dbpassword = "";
                    String message = "";
                    String createtime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());

                    if (dbresult.get("code").equals(200)) {
                        String dbPath = dbresult.get("dbpath").toString();
                        String dbPass = dbresult.get("dbpass").toString();
                        dbpassword = dbPass;
                        String dbOBSAddress = "qualityInspection/" + xzqdm + ".db";
                        AtomicInteger attemptCount = new AtomicInteger(0);
                        String dbOBSlog;
                        do {
                            dbOBSlog = OBSUploadUnits.OBSUpload(dbOBSAddress, dbPath);
                            attemptCount.incrementAndGet();
                        } while (!"success".equals(dbOBSlog) && attemptCount.get() < 5);
                        dburl = "https://obs-top.obs.cn-north-1.myhuaweicloud.com/" + dbOBSAddress;
                        message = dbresult.get("message").toString();
                    } else {
                        message = dbresult.get("message").toString();
                    }

                    map.put("xzqdm", xzqdm);
                    map.put("dburl", dburl);
                    map.put("message", message);
                    map.put("dbpassword", dbpassword);
                    map.put("createtime", createtime);

                    wpzfDockMapper.updateQualitytesting(map); // 更新数据库

                    return null; // 因为我们不关心任务的返回值
                }
            };
            futures.add(executorService.submit(task)); // 提交任务并保存Future对象（尽管我们在这里不使用它）
        }
        executorService.shutdown(); // 关闭线程池，等待所有任务完成
    }



    @RequestMapping("t2")
    public AjaxResult t3() {
        List<Map<String, Object>> list = wpzfNdhcInfoTranslateServiceImpl.t2();
        Integer rest = 0;
        Map<String,Object> m=new HashMap<>();
        for (Map<String, Object> map : list) {
            String xzqdm = map.get("xzqdm") + "";
            //获取每个行政区代码下tb数量
            int nCount= wpSjsbNdDTOMapper.getSjsbtbcount(xzqdm);
            if(nCount>0)
            {
                String value="";
                String stage="";
                int nMaxRecord = 2000;
                int nStage = (int)Math.ceil(nCount / (1.0 * nMaxRecord));
                for (int p = 0; p < nStage; p++)
                {
                    value=xzqdm+"-"+(p + 1);
                    m.put("xzqdm",value);
                    wpzfDockMapper.saveQualitytesting(m);//插入任务表


                    m.put("xzqdm",xzqdm);
                    m.put("stage",value);
                    m.put("limitValue",nMaxRecord);
                    m.put("offsetValue",nMaxRecord * p);
                    int k=wpzfNdhcInfoTranslateServiceImpl.updateValue(m);

                }
            }
        }
        return AjaxResult.success("成功", rest);
    }

}
